package vip.sone.eureka.consumer.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author winstone jianwenzhen@qq.com
 * @date 19-4-12 下午4:42
 */
@Slf4j
@RestController
public class ConsumerController {

	@Autowired
	RestTemplate restTemplate;

	/**
	 * 注入负载均衡客户端
	 * 负载均衡规则是轮询
	 */
	@Autowired
	LoadBalancerClient loadBalancerClient;

	@GetMapping("/consume")
	public String consume() {
		// 从负载均衡器中选出一个生产者实例
		ServiceInstance serviceInstance = loadBalancerClient.choose("eureka-client");
		String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/product";
		log.info("url: {}", url);
		// 通过RestTemplate调用服务接口
		return restTemplate.getForObject(url, String.class);
	}
}
